package com.ecloud.common.web.config;

import java.util.Locale;

import org.hibernate.validator.HibernateValidatorConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 校验配置
 *
 * @author LiuGangQiang Create in 2020/03/30
 */
@Configuration
public class AutoValidatorConfiguration implements WebMvcConfigurer {

    /**
     * 资源文件数据源配置
     *
     * @author LiuGangQiang Create in 2021/08/05
     * @return {@link ResourceBundleMessageSource}
     */
    private ResourceBundleMessageSource messageSource() {
        /* 设置资源文件 */
        ResourceBundleMessageSource rbms = new ResourceBundleMessageSource();
        /* 设置编码 */
        rbms.setDefaultEncoding("UTF-8");
        /* 设置资源路径 */
        rbms.setBasenames("i18n/validator");
        /* 设置刷新时间为30分钟 默认"-1" 表示不刷新 */
        /* rbms.setCacheSeconds(60 * 30); */
        /* 设置默认语言环境 */
        rbms.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return rbms;
    }

    /**
     * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurer#getValidator()
     */
    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        /* 设置资源文件数据源 */
        localValidatorFactoryBean.setValidationMessageSource(messageSource());
        /* 开启快速失败模式 */
        localValidatorFactoryBean.getValidationPropertyMap().put(HibernateValidatorConfiguration.FAIL_FAST, "true");
        return localValidatorFactoryBean;
    }
}
